from pathlib import Path

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QVBoxLayout, QGridLayout, QPushButton, QWidget, QLabel

from common.excel import Excel
from components.load_widget import LoadingDialog
from components.widget.msg import MessageBox
from components.widget.q_thread import SHPThread
from components.widget.small_frame import FileTextLabel, ComboBoxLabel


class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.shp = SHPThread()
        self.initUI()

        self.loadDialog = LoadingDialog(self)
        self.loadDialog.hide()
        self.loadDialog.raise_()

        def load_value(xlsx, status, schedule):
            if status == '成功':
                _log = '<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">' \
                       f'<span style=" color:#4cc700;">{xlsx}, 成功</span></p>'
            else:
                _log = '<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">' \
                       f'<span style=" color:#ff1744;">{xlsx}, 失败！！！！</span></p>'
            self.loadDialog.setHtml(_log)
            if status != '成功':
                self.loadDialog.setText(status)
            self.loadDialog.setValue(schedule)

        self.shp.started.connect(self.loadDialog.show)
        self.shp.log.connect(load_value)
        self.shp.finished.connect(lambda: self.loadDialog.setEnabled(True))

        self._setQss()

    def _setQss(self):
        self.setObjectName('MainWindow')
        self.setStyleSheet(
            '''
            * {
                font: 13pt 'Segoe UI', 'Microsoft YaHei', 'PingFang SC';
            }
            #MainWindow { background-color: #fff; }
            QFrame#MessageBox {
                background-color: rgba(0, 0, 0, 0.65);
                border-radius: 5px;
            }
            
            QLabel#textLabel {
                background-color: transparent;
                color: white;
                font: 13pt 'Segoe UI', 'Microsoft YaHei', 'PingFang SC';
                text-align: center;
            }
            '''
        )

    def initUI(self):
        self.setWindowTitle('XLSX转SHP文件小工具')

        self.vBox = QVBoxLayout(self)
        self.vBox.setContentsMargins(20, 20, 20, 20)
        self.vBox.setSpacing(20)
        self.vBox.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.titleLabel = QLabel('XLSX转SHP文件小工具')
        self.titleLabel.setStyleSheet("font: 20pt 'Segoe UI', 'Microsoft YaHei', 'PingFang SC';")
        self.vBox.addWidget(self.titleLabel, 0, Qt.AlignCenter)

        self.openDirLabel = FileTextLabel(_type='openDir')
        self.openDirLabel.setLabelText("xlsx文件路径：")
        self.vBox.addWidget(self.openDirLabel)

        self.saveFileLabel = FileTextLabel(_type='saveFile')
        self.saveFileLabel.setLabelText("保存shp文件路径：")
        self.vBox.addWidget(self.saveFileLabel)

        self.openFileLabel = FileTextLabel(_type='openFile')
        self.openFileLabel.setLabelText("模板文件路径：")
        self.openFileLabel.clicked.connect(self.openFileLabel_clicked_event)
        self.vBox.addWidget(self.openFileLabel)

        self.gridLayout = QGridLayout()
        self.typeLabel = ComboBoxLabel()
        self.x = ComboBoxLabel()
        self.y = ComboBoxLabel()
        self.z = ComboBoxLabel()
        self.m = ComboBoxLabel()
        self.coding = ComboBoxLabel()
        self.typeLabel.setLabelText('数据类型：')
        self.x.setLabelText('经度(x)：')
        self.y.setLabelText('纬度(y)：')
        self.z.setLabelText('仰角值(z)：')
        self.m.setLabelText('度量值(m)：')
        self.coding.setLabelText('编码格式：')

        self.typeLabel.addItems(['点', '线', '面'])
        self.typeLabel.setCurrentIndex(1)
        self.coding.addItems(['UTF-8', 'GBK', 'GB2312', 'GB18030'])
        self.coding.setCurrentIndex(0)

        self.gridLayout.addWidget(self.typeLabel, 0, 0)
        self.gridLayout.addWidget(self.x, 0, 1)
        self.gridLayout.addWidget(self.y, 0, 2)
        self.gridLayout.addWidget(self.z, 1, 0)
        self.gridLayout.addWidget(self.m, 1, 1)
        self.gridLayout.addWidget(self.coding, 1, 2)
        self.vBox.addLayout(self.gridLayout)

        self.pushButton = QPushButton('开始')
        self.pushButton.setFixedSize(400, 40)
        self.pushButton.clicked.connect(self.pushButton_clicked_connect)

        self.vBox.addWidget(self.pushButton, 0, Qt.AlignHCenter)

    def getExcelHeaders(self, file):
        ex = Excel(file)
        return ex.getHeaders()

    def openFileLabel_clicked_event(self, file):
        headers = ['', *self.getExcelHeaders(file)]
        for i in [self.x, self.y, self.z, self.m]:
            i.addItems(headers)
            i.setCurrentIndex(-1)

    def pushButton_clicked_connect(self):
        if self._judgmentFile(self.openDirLabel.lineEditText(), 'xlsx') is False:
            return
        if self._judgmentFile(self.saveFileLabel.lineEditText(), 'shp') is False:
            return
        if self._judgmentFile(self.openFileLabel.lineEditText(), '模板') is False:
            return
        columns = []
        if not self.x.currentText():
            MessageBox.info(self, f'请选择经度(x)')
            return
        else:
            columns.append(self.x.currentText())
        if not self.y.currentText():
            MessageBox.info(self, f'请选择纬度(y)')
            return
        else:
            columns.append(self.y.currentText())
        if self.z.currentText():
            columns.append(self.z.currentText())
        if self.m.currentText():
            columns.append(self.m.currentText())

        typeCurrentText = self.typeLabel.currentText()
        _type = '线'
        if len(columns) == 2:
            if typeCurrentText == '点':
                _type = 'point'
            elif typeCurrentText == '线':
                _type = 'line'
            elif typeCurrentText == '面':
                _type = 'poly'
        elif len(columns) == 3:
            if not self.m.currentText():
                MessageBox.info(self, '请选择度量值(m)')
                return
            if typeCurrentText == '点':
                _type = 'pointm'
            elif typeCurrentText == '线':
                _type = 'linem'
            elif typeCurrentText == '面':
                _type = 'polym'
        elif len(columns) == 4:
            if typeCurrentText == '点':
                _type = 'pointz'
            elif typeCurrentText == '线':
                _type = 'linez'
            elif typeCurrentText == '面':
                _type = 'polyz'

        self.shp.setValue(
            filedir=self.openDirLabel.lineEditText(),
            saveFile=self.saveFileLabel.lineEditText(),
            columns=columns,
            element_type=_type,
            encoding=self.coding.currentText()
        )
        self.shp.start()

    def _judgmentFile(self, text: str, _t: str):
        if len(text) == 0:
            MessageBox.info(self, f'请选择{_t}文件路径')
            return False
        if _t == 'xlsx':
            if not Path(text).is_dir():
                MessageBox.info(self, f'{text}, 不存在')
                return False
        elif _t == '模板':
            if not Path(text).is_file():
                MessageBox.info(self, f'{text}, 不存在')
                return False
        elif _t == 'shp':
            file = Path(text).resolve().parent
            if not file.is_dir():
                MessageBox.info(self, f'{file}, 不存在')
                return False
        return True
